package com.qunar.qcf.handler.web;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 提供对tomcat7的http协议和servlet3.0规范异步支持
 * @author zhangwan
 * @email wan.zhang@qunar.com
 *
 */
public class AsyncInvoker {
	private final static AsyncInvoker singleton = new AsyncInvoker();
	private final ExecutorService executor = Executors.newCachedThreadPool();
	
	private AsyncInvoker() {
	}

	public static void execute(HttpServletRequest request, HttpServletResponse response, AsyncResult result) {
		AsyncContext context = request.startAsync();
		context.setTimeout(0);
		singleton.startupWorker(context, result);
	}
	
	private void startupWorker(AsyncContext context, AsyncResult result) {
		Worker worker = new Worker(context, result);
		executor.execute(worker);
	}

	class Worker implements Runnable {
		private AsyncContext context;
		private AsyncResult result;

		public Worker(AsyncContext context, AsyncResult result) {
			this.context = context;
			this.result = result;
		}

		@Override
		public void run() {
			HttpServletResponse response = (HttpServletResponse) context.getResponse();
			HttpServletRequest request = (HttpServletRequest) context.getRequest();
			result.processer(request, response);
			context.complete();
		}
	}

}
